package com.bugbuff.dubbo.server.service;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.bugbuff.common.mapper.UserMapper;
import com.bugbuff.common.pojo.User;
import com.bugbuff.common.utils.UserThreadLocal;
import com.bugbuff.common.vo.ErrorResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class UserService {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${tanhua.sso.url}")
    private String ssoUrl;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private UserMapper userMapper;

    //解析token获取User对象
    public User queryToken(String token){
        //User user = ...
        String url = ssoUrl + "/user/" + token;
        User user = restTemplate.getForObject(url, User.class);
        if (user == null) {
            return null;
        }
        return user;
    }

    /**
     * 校验验证码
     * @param mobile
     * @param checkCode
     * @return
     */
    public Boolean checkVerificationCode(String mobile, String checkCode) {
        String redisKey = "CHECK_CODE_" + mobile;
//        1、从Redis中获取验证码
        String redisCode = redisTemplate.opsForValue().get(redisKey);
//        2、与code比较
        if (!ObjectUtil.equal(redisCode,checkCode)) {//        2.1、验证码不一致，登录失败
//            return ErrorResult.builder().errCode("000002").errMessage("验证码不一致！").build();
            return false;
        }
        //验证码一致，验证结束，删除验证码
        redisTemplate.delete(redisKey);
        return true;
    }


    /**
     * 修改手机号
     * @param id
     * @param phone
     * @return
     */
    public ErrorResult updatePhoneByUserId(Long id, String phone) {
        QueryWrapper<User> queuy=new QueryWrapper<>();
        queuy.eq("mobile",phone);
        Integer count = userMapper.selectCount(queuy);
        if (count>0){
           return ErrorResult.builder().errCode("00001").errMessage("该手机号已存在！").build();
        }
        try {
            User user=new User();
            user.setMobile(phone);
            LambdaUpdateWrapper<User> updateWrapper= new LambdaUpdateWrapper();
            updateWrapper.eq(User::getId,id);
            int updateCount = userMapper.update(user, updateWrapper);
            if(updateCount>0){
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ErrorResult.builder().errCode("00002").errMessage("手机号修改失败！").build();
    }
}
